using Godot;
using System;
using System.Collections.Generic;

namespace RPG01.Scripts.SateMachine;

public partial class StateMachine : Node
{
    private State currentState;

    private Dictionary<Type, State> stateMap = new Dictionary<Type, State>();

    public void ClearStateAll()
    {
        stateMap.Clear();
    }

    public void AddState(State state)
    {
        var type = state.GetType();
        if (stateMap.ContainsKey(type))
        {
            GD.PushWarning($"类型 {type.Name} 已存在");
            return;
        }
        stateMap.Add(type, state);
    }
    
    public void SwitchState<T>()
    {
        var state = GetState<T>();
        if (state == null)
        {
            GD.PushWarning($"找不到类型 {typeof(T).Name} 的实例");
            return;
        }
        
        currentState?.Exit();
        currentState = state;
        currentState.Enter();
    }

    private State GetState<T>()
    {
        if (stateMap.TryGetValue(typeof(T), out var state))
            return state;
        return null;
    }
    
    public override void _Process(double delta)
    {
        currentState?.Process(delta);
    }

    public override void _PhysicsProcess(double delta)
    {
        currentState?.PhysicsProcess(delta);
    }
}